import njust.csc.aecore.utils.ImageUtils
import org.opencv.core.Core
import org.opencv.core.Mat
import org.opencv.imgcodecs.Imgcodecs
import org.opencv.imgproc.Imgproc
import java.util.*
import kotlin.io.path.*
import kotlin.test.Test


/**
 * @Author ZhouHang
 * @Date 24/7/2 周二
 */
class OpencvTest {
    @Test fun `Test Environment`() {
        println(Core.NATIVE_LIBRARY_NAME)
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME)
    }

    @Test fun `Test Opencv`() {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME)
        // 读取两张图像。准备比对的图片
        val image1 = Imgcodecs.imread("N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\userInput\\ac6ae201b2b4e918c66c9d61d4a65e3c\\step-2--g0a4-1719933587519.png")
        val image2 = Imgcodecs.imread("N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\userInput\\ac6ae201b2b4e918c66c9d61d4a65e3c\\step-24--g0a2-1719933600481.png")

        // 计算相似性指数
        val ssim = ImageUtils.calculateSimilarity(image1, image2)
        println("相似性指数: $ssim")

        image1.release()
    }

    @Test fun `Test filter Image`() {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME)
        val img = "N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\userInput\\ac6ae201b2b4e918c66c9d61d4a65e3c\\step-2--g0a4-1719933587519.png"

        val src = Imgcodecs.imread(img)
        val size = src.width() * src.height()

        val gray = Mat()
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY)
        src.release()

        // Binary thresholding
        val binary = Mat()
        Imgproc.threshold(gray, binary, 200.0, 255.0, Imgproc.THRESH_BINARY)
        gray.release()

        val blankArea = Core.countNonZero(binary)
        binary.release()

        println("空白区域比例: ${blankArea / size.toDouble()}")
    }

    @Test fun `Test Rotate`() {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME)
        val img =
            "N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\screencaps\\com.o2j66w.fgyvrr\\step-21--g0a2-1720091168500.png"
        val src = Imgcodecs.imread(img)
        val tgt = ImageUtils.rotate90(src)
        Imgcodecs.imwrite("N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\screencaps\\com.o2j66w.fgyvrr\\1\\a.png", tgt);
    }

    @Test fun `Test Base64 Encode`() {
        val file = Path("N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\screencaps\\com.o2j66w.fgyvrr\\step-1--g0a0-1720091136217.png")
        val str = ImageUtils.base64Encode(file)
        val txtFile = Path("N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\screencaps\\com.o2j66w.fgyvrr\\a.txt")
        txtFile.writeText(str)
    }

    @Test fun `Test Base64 Decode`() {
        val txtFile = Path("N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\screencaps\\com.o2j66w.fgyvrr\\a.txt")
        val str = ImageUtils.base64Decode(txtFile.readText())
        val file = Path("N:\\Code\\PL\\StaticAnalysis\\ApkExplorer\\output\\screencaps\\com.o2j66w.fgyvrr\\a.png")
        file.writeBytes(str)
    }
}